<?php
namespace app\admin\model;
use think\Model;

class Goods extends Model 
{
	protected $field = true;
	protected static function init(){
		Goods::beforeInsert(function ($goods){
			if($_FILES['og_thumb']['tmp_name']){
				$thumbName = $goods->upload('og_thumb');
				// dump($_FILES);die;
				$ogThumb =date("Ymd").DS.$thumbName;
				$bigThumb=date("Ymd").DS.'big_'.$thumbName;
				$midThumb=date("Ymd").DS.'mid_'.$thumbName;
				$smThumb=date("Ymd").DS.'sm_'.$thumbName;
				 // dump($ogThumb);die;
				$image = \think\Image::open(IMG_UPLOADS.DS.$ogThumb);
				$image->thumb(config('big_thumb_width'),config('big_thumb_height'))->save(IMG_UPLOADS.DS.$bigThumb);
				$image->thumb(config('mid_thumb_width'),config('mid_thumb_height'))->save(IMG_UPLOADS.DS.$midThumb);
				$image->thumb(config('sm_thumb_width'),config('sm_thumb_height'))->save(IMG_UPLOADS.DS.$smThumb);
				 $goods->og_thumb=$ogThumb;
				 $goods->big_thumb=$bigThumb;
				 $goods->mid_thumb=$midThumb;
				 $goods->sm_thumb=$smThumb;
			}
			
			 $goods->goods_code=time().rand(111111,999999);//商品编号
			 // dump($ogThumb);die;
		});
		Goods::afterInsert(function($goods){
			//接收表单数据
			$goodsData = input('post.');
			//批量写入会员价格
			$mpriceArr=$goods->mp;
			$goodsId = $goods->id;
			if($mpriceArr){
				foreach ($mpriceArr as $k => $v){
					if(trim($v)== ''){
						continue;
					}else{
						db('member_price')->insert(['mlevel_id'=>$k,'mprice'=>$v,'goods_id'=>$goodsId]);
					}
				}
			}  
			//处理商品推荐位
			if(isset($goodsData['recpos'])){
				foreach($goodsData['recpos'] as $k => $v){
					db('rec_item')->insert(['recpos_id'=>$v,'value_id'=>$goodsId,'value_type'=>1]);
				}
			}
			
			//处理商品请求   获取页面数据的方式 $goods->goods_attr  $data = input("post.")
			$i = 0;    
			if(isset($goodsData['goods_attr'])){
				foreach($goodsData['goods_attr'] as $k => $v){
					if(is_array($v)){
						if(!empty($v)){
							//若是数组  遍历时 i累计下标  用下表直接取值插入数据
							foreach($v as $k1 => $v1){
								if(!$v1){
									$i++;
									continue;
									
								}
								db('goods_attr')->insert(['attr_id' =>$k,'attr_value'=>$v1,'attr_price'=>$goodsData['attr_price'][$i],'goods_id'=>$goodsId]);
								$i++;
							}
						}
					}
					else{
						//处理唯一属性类型
						db('goods_attr')->insert(['attr_id' =>$k,'attr_value'=>$v,'goods_id'=>$goodsId]);
						
					}
				}
			}
			// dump($_FILES);die;
			if($goods->_hasImgs($_FILES['goods_photo']['tmp_name'])){
				dump($_FILES);
				$files = request()->file('goods_photo');
				//将文件移动到框架应用的根目录下/pulbic/uploads/目录下
				// dump($files);die;
				foreach ($files as $file){
					$info = $file->move(ROOT_PATH . 'public' .DS .'static'.DS.'uploads');
					// dump($info);die;
					if($info){
                        // 输出 42a79759f284b767dfcb2a0197904287.jpg
                        $photoName=$info->getFilename();
                        $ogphoto=date("Ymd"). DS . $photoName;
                        $bigphoto=date("Ymd"). DS . 'big_'.$photoName;
                        $midphoto=date("Ymd"). DS . 'mid_'.$photoName;
                        $smphoto=date("Ymd"). DS . 'sm_'.$photoName;
						

						//图片处理
						//  echo IMG_UPLOADS.DS.$ogphoto;
                        $image = \think\Image::open(IMG_UPLOADS.DS.$ogphoto);
                         $image->thumb(config('big_thumb_width'), config('big_thumb_height'))->save(IMG_UPLOADS.DS.$bigphoto);
						//  dump('a');
                         $image->thumb(config('mid_thumb_width'), config('mid_thumb_height'))->save(IMG_UPLOADS.DS.$midphoto);
                         $image->thumb(config('sm_thumb_width'), config('sm_thumb_height'))->save(IMG_UPLOADS.DS.$smphoto);
                        // @unlink(IMG_UPLOADS.DS.$ogphoto);//删除原图
                        db('goods_photo')->insert(['goods_id'=>$goodsId,'og_photo'=>$ogphoto,'big_photo'=>$bigphoto,'mid_photo'=>$midphoto,'sm_photo'=>$smphoto]);
                    }else{
                        // 上传失败获取错误信息
                        echo $file->getError();
                    } 
					
				}
			}
		});
		
		Goods::beforeUpdate(function ($goods) {
			//商品的id
			$goodsId = $goods->id;
			
			//处理商品请求   获取页面数据的方式 $goods->goods_attr  $data = input("post.")
			$goodsData = input('post.');
		   db('rec_item')->where(array('value_type'=>1,'value_id'=>$goodsId))->delete();
			if(isset($goodsData['recpos'])){
				foreach($goodsData['recpos'] as $k => $v){
				db('rec_item')->insert(['recpos_id'=>$v,'value_id'=>$goodsId,'value_type'=>1]);
				}
			}	
		   if(isset($goodsData['goods_attr'])){
					$i = 0; 
				foreach($goodsData['goods_attr'] as $k => $v){
					if(is_array($v)){
						if(!empty($v)){
							//若是数组  遍历时 i累计下标  用下表直接取值插入数据
							foreach($v as $k1 => $v1){
								if(!$v1){
									$i++;
									continue;
									
								}
								db('goods_attr')->insert(['attr_id' =>$k,'attr_value'=>$v1,'attr_price'=>$goodsData['attr_price'][$i],'goods_id'=>$goodsId]);
								$i++;
							}
						}
					}
					else{
						//处理唯一属性类型
						db('goods_attr')->insert(['attr_id' =>$k,'attr_value'=>$v,'goods_id'=>$goodsId]);
						
					}
				}
			}
			//修改商品属性
			if(isset($goodsData['old_goods_attr'])){   //if(isset($goodsData['old_goods_attr'])){
				$attrPrice = $goodsData['old_attr_price'];
				$idsArr = array_keys($attrPrice);
				$valuesArr=array_values($attrPrice);
				
				$i = 0; 
				foreach($goodsData['old_goods_attr'] as $k => $v){
					if(is_array($v)){
						if(!empty($v)){
							//若是数组  遍历时 i累计下标  用下表直接取值插入数据
							foreach($v as $k1 => $v1){
								if(!$v1){
									$i++;
									continue;
								}
								db('goods_attr')->where('id','=',$idsArr[$i])->update(['attr_value'=>$v1,'attr_price'=>$valuesArr[$i]]);
								$i++;
							}
						}
					}
					else{
						  // 处理唯一属性类型
						                        db('goods_attr')->where('id','=',$idsArr[$i])->update(['attr_value'=>$v,'attr_price'=>$valuesArr[$i]]);
						                        $i++;
					}
				}
			}
			
			//商品相册处理
			if($goods->_hasImgs($_FILES['goods_photo']['tmp_name'])){
				dump($_FILES);
				$files = request()->file('goods_photo');
				//将文件移动到框架应用的根目录下/pulbic/uploads/目录下
				// dump($files);die;
				foreach ($files as $file){
					$info = $file->move(ROOT_PATH . 'public' .DS .'static'.DS.'uploads');
					// dump($info);die;
					if($info){
			            // 输出 42a79759f284b767dfcb2a0197904287.jpg
			            $photoName=$info->getFilename();
			            $ogphoto=date("Ymd"). DS . $photoName;
			            $bigphoto=date("Ymd"). DS . 'big_'.$photoName;
			            $midphoto=date("Ymd"). DS . 'mid_'.$photoName;
			            $smphoto=date("Ymd"). DS . 'sm_'.$photoName;
						
			
						//图片处理
						//  echo IMG_UPLOADS.DS.$ogphoto;
			            $image = \think\Image::open(IMG_UPLOADS.DS.$ogphoto);
			             $image->thumb(config('big_thumb_width'), config('big_thumb_height'))->save(IMG_UPLOADS.DS.$bigphoto);
						//  dump('a');
			             $image->thumb(config('mid_thumb_width'), config('mid_thumb_height'))->save(IMG_UPLOADS.DS.$midphoto);
			             $image->thumb(config('sm_thumb_width'), config('sm_thumb_height'))->save(IMG_UPLOADS.DS.$smphoto);
			            // @unlink(IMG_UPLOADS.DS.$ogphoto);//删除原图
			            db('goods_photo')->insert(['goods_id'=>$goodsId,'og_photo'=>$ogphoto,'big_photo'=>$bigphoto,'mid_photo'=>$midphoto,'sm_photo'=>$smphoto]);
			        }else{
			            // 上传失败获取错误信息
			            echo $file->getError();
			        } 
					
				}
			}
			
			
			//处理会员价格
			$mpriceArr = $goods->mp;
			
			$mp=db('member_price');
			//删除原有的会员价格
			$mp->where('goods_id','=',$goodsId)->delete();
			//批量写入会员价格
			if($mpriceArr){
				foreach($mpriceArr as $k=>$v){
					if(trim($v) == ''){
						continue;
					}else{
						$mp->insert(['mlevel_id'=>$k,'mprice'=>$v,'goods_id'=>$goodsId]);
					}
				}
			}
			//修改商品之前,如果有上传的新缩略图,先处理图片
		   if($_FILES['og_thumb']['tmp_name']){
			   //若有旧的图片存在就删除旧的图片
			   @unlink(IMG_UPLOADS.DS.$goods->og_thumb);
			   @unlink(IMG_UPLOADS.DS.$goods->big_thumb);
			   @unlink(IMG_UPLOADS.DS.$goods->mid_thumb);
			   @unlink(IMG_UPLOADS.DS.$goods->sm_thumb);
		       $thumbName=$goods->upload('og_thumb');
		       $ogThumb=date("Ymd"). DS . $thumbName;
		       $bigThumb=date("Ymd"). DS . 'big_'.$thumbName;
		       $midThumb=date("Ymd"). DS . 'mid_'.$thumbName;
		       $smThumb=date("Ymd"). DS . 'sm_'.$thumbName;
		       $image = \think\Image::open(IMG_UPLOADS.DS.$ogThumb);
		       $image->thumb(config('big_thumb_width'), config('big_thumb_height'))->save(IMG_UPLOADS.DS.$bigThumb);
		       $image->thumb(config('mid_thumb_width'), config('mid_thumb_height'))->save(IMG_UPLOADS.DS.$midThumb);
		       $image->thumb(config('sm_thumb_width'), config('sm_thumb_height'))->save(IMG_UPLOADS.DS.$smThumb);
		       $goods->og_thumb=$ogThumb;
		       $goods->big_thumb=$bigThumb;
		       $goods->mid_thumb=$midThumb;
		       $goods->sm_thumb=$smThumb;
		   }
		  });
		Goods::beforeDelete(function($goods){
			// dump($goods);die;
			$goodsId = $goods ->id;
			//若该商品设为了推荐,则删除其推荐的记录
			db('recItem')->where(array('value_id'=>$goodsId,'value_type'=>1))->delete();
			//删除主图机器缩略图
			if($goods->og_thumb){
				$thumb=[];
				//使用一个空数组接收for删除
				$thumb[] = IMG_UPLOADS.DS.$goods->og_thumb;
				$thumb[] = IMG_UPLOADS.DS.$goods->big_thumb;
				$thumb[] = IMG_UPLOADS.DS.$goods->mid_thumb;
				$thumb[] = IMG_UPLOADS.DS.$goods->sm_thumb;
				foreach ($thumb as $k => $v){
					if(file_exists($v)){
						@unlink($v);
					}
				}
			}
			//删除关联的会员价格
			db('member_price')->where('goods_id','=',$goodsId)->delete();
			//删除关联的商品属性
			db('goods_attr')->where('goods_id','=' ,$goodsId)->delete();
			//删除关联的商品相册
			$goodsPhotoRes = model('GoodsPhoto')->where('goods_id','=',$goodsId)->select();
					if(!empty($goodsPhotoRes)){
						foreach($goodsPhotoRes as $k => $v){
							if($v->og_photo){
								$photo=[];
								//使用一个空数组接收for删除
								$photo[] = IMG_UPLOADS.DS.$v->og_photo;
								$photo[] = IMG_UPLOADS.DS.$v->big_photo;
								$photo[] = IMG_UPLOADS.DS.$v->mid_photo;
								$photo[] = IMG_UPLOADS.DS.$v->sm_photo;
								foreach($photo as $k1=> $v1){
									if(file_exists($v1)){
								@unlink($v1);
									}
								}
						}
					}
				}
				model('GoodsPhoto')->where('goods_id','=',$goodsId)->delete();
			// dump($goodsPhotoRes);die;
		});
	}
	// 商品相册是否有图片上传判断
    private function _hasImgs($tmpArr){
        foreach ($tmpArr as $k => $v) {
            if($v){
                return true;
            }
        }
        return false;
    }

	public function upload($imgName){
	    // 获取表单上传文件 例如上传了001.jpg
	    $file = request()->file($imgName);
	    
	    // 移动到框架应用根目录/public/uploads/ 目录下
	    if($file){
	        $info = $file->move(ROOT_PATH.'public'.DS.'static'.DS.'uploads');
	        if($info){
	            // 成功上传后 获取上传信息
	            // 输出 jpg
	            // echo $info->getExtension();
	            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
	            // echo $info->getSaveName();
	            // 输出 42a79759f284b767dfcb2a0197904287.jpg
	            return $info->getFilename(); 
	        }else{
	            // 上传失败获取错误信息
	            echo $file->getError();
	        }
	    }
	}
}
